import tornado.web
import tornado.httpclient
import hashlib
import threading
import datetime
import random
import sys
import traceback
import ioloop

class ThreadClass(threading.Thread):
    def __init__(self, counter):
        self.count = counter
        threading.Thread.__init__(self)
    
    def run(self):
        now = datetime.datetime.now()
        partnerId = random.randrange(50000, 50005)
	
	#http_client = tornado.httpclient.HTTPClient()	
	async_http_client = tornado.httpclient.AsyncHTTPClient()	
	for i in range(self.count):
	    random.seed()
	    hash = random.getrandbits(128)
	    print "[%s] %s - (%s) %016x" % (self.getName(), now, partnerId, hash)
	    
	    try:	        
		#response = http_client.fetch("http://localhost/%s/%016x" % (partnerId, hash), self_handle_response)
	        url = "http://localhost/%s/%016x" % (partnerId, hash) 
	        async_http_client.fetch(url, callback=self.handle_response)
	        ioloop.IOLoop.instance().start()
		#print response
            except:
	        print self.formatExceptionInfo()
 
    def handle_response(self, response):
        if response.error:
            print "Error:", response.error
        else:
            print response.body
	
        print response
        ioloop.IOLoop.instance().stop()


    def formatExceptionInfo(maxTBlevel=5):
        cla, exc, trbk = sys.exc_info()
        excName = cla.__name__
        try:
            excArgs = exc.__dict__["args"]
        except KeyError:
            excArgs = "<no args>"
        
        excTb = traceback.format_tb(trbk, maxTBlevel)
        return (excName, excArgs, excTb)


threads = 10
calls = 1
for i in range(threads):
    t = ThreadClass(calls)
    t.start()
